package com.xiaoshuidi.cloud.module.contract.controller.admin.contract;

import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.operatelog.core.annotations.OperateLog;
import com.xiaoshuidi.cloud.module.contract.controller.admin.contract.vo.ElectronicContractGenerateRespVO;
import com.xiaoshuidi.cloud.module.contract.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.contract.service.contract.ElectronicContractService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import static com.xiaoshuidi.cloud.framework.common.pojo.CommonResult.success;
import static com.xiaoshuidi.cloud.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 电子合同")
@RestController
@RequestMapping(ApiConstants.NAME + "/electronic-contract")
@Validated
public class ElectronicContractController {

    @Resource
    private ElectronicContractService electronicContractService;

    @GetMapping("/generate")
    @Operation(summary = "生成电子合同")
    @Parameter(name = "contractId", description = "合同id", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('contract:generate')")
    public CommonResult<ElectronicContractGenerateRespVO> generateElectronicContract(@RequestParam("contractId") Long contractId) {
        return success(electronicContractService.generateElectronicContract(contractId));
    }

    @GetMapping("/autoSign")
    @Operation(summary = "电子签约（甲方）")
    @Parameter(name = "contractId", description = "合同id", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('contract:auto-sign')")
    public CommonResult<ElectronicContractGenerateRespVO> electronicContractAutoSign(@RequestParam("contractId") Long contractId) {
        return success(electronicContractService.autoSign(contractId));
    }

    /**
     * 预览下载合同
     */
    @GetMapping("/view-download")
    @Operation(summary = "预览下载合同")
    //    @PreAuthorize("@ss.hasPermission('contract:owner:export')")
    @OperateLog(type = EXPORT)
    public void exportHouseOwnerExcel(@RequestParam("contractId") Long contractId,HttpServletResponse response) throws Exception {
        String downloadUrl = electronicContractService.getDownloadUrl(contractId);
        if (StringUtils.isBlank(downloadUrl)){
            return;
        }
        //new一个URL对象
        URL url = new URL(downloadUrl);
        //打开链接
        URLConnection conn = url.openConnection();
        //超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(inStream);
        OutputStream outStream=response.getOutputStream();//输出数据
        //写入数据
        outStream.write(data);
        outStream.flush();
        //关闭输出流
        outStream.close();
    }

    private byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[4096];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


    /**
     * 生成业主电子合同
     */
    @GetMapping("/own-generate")
    @Operation(summary = "生成业主电子合同")
    @Parameter(name = "contractId", description = "合同id", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('contract:generate')")
    public CommonResult<ElectronicContractGenerateRespVO> generateOwnerElectronicContract(@RequestParam("contractId") Long contractId) {
        return success(electronicContractService.generateOwnerElectronicContract(contractId));
    }

    /**
     * 业主合同电子签约（甲方）
     */
    @GetMapping("/owner-auto-sign")
    @Operation(summary = "业主合同电子签约（甲方）")
    @Parameter(name = "contractId", description = "合同id", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('contract:auto-sign')")
    public CommonResult<ElectronicContractGenerateRespVO> ownerElectronicContractAutoSign(@RequestParam("contractId") Long contractId) {
        return success(electronicContractService.ownerAutoSign(contractId));
    }


}
